import os

from alipay import AliPay
from django.conf import settings
from django.http import JsonResponse
from django.views import View
# Create your views here.
from meiduo_mall.utils.mixins import LoginRequiredMixin


# /payment/(?P<order_id>\d+)/
from orders.models import OrderInfo
from payment.models import Payment


class PaymentURLView(LoginRequiredMixin, View):
    @staticmethod
    def get(request, order_id):
        user = request.user

        try:
            order = OrderInfo.objects.get(user=user,
                                          order_id=order_id,
                                          status=1)
        except Exception:
            return JsonResponse({'code': 0,
                                 'message': '订单信息有误!'})

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                              "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                              "keys/alipay_public_key.pem"),
            sign_type='RSA2',
            debug=settings.ALIPAY_DEBUG
        )
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject=f'美多商城{order_id}',
            return_url=settings.ALIPAY_RETURN_URL
        )

        alipay_url = settings.ALIPAY_URL + '?' + order_string
        return JsonResponse({'code': 0,
                             'message': 'OK',
                             'alipay_url': alipay_url})


# PUT /payment/status/
class PaymentStatusView(LoginRequiredMixin, View):
    @staticmethod
    def put(request):
        req_data = request.GET.dict()

        signature = req_data.pop('sign')

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                              "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),
            sign_type='RSA2',
            debug=settings.ALIPAY_DEBUG
        )

        success = alipay.verify(req_data, signature)

        if success:
            order_id = req_data.get('out_trade_no')
            trade_id = req_data.get('trade_no')

            Payment.objects.create(order_id=order_id,
                                   trade_id=trade_id)

            OrderInfo.objects.filter(order_id=order_id,
                                     status=1).update(status=2)

            # ③ 返回响应
            return JsonResponse({'code': 0,
                                 'message': 'ok',
                                 'trade_id': trade_id})

        else:
            # 订单支付失败，返回相应提示
            return JsonResponse({'code': 400,
                                 'message': '支付出错!非法请求!'})